iT邦幫忙

2025 iThome 鐵人賽

DAY 15
0
Vue.js

Vue 新手學習紀錄系列 第 15

Day 15 | Slot 是什麼

  • 分享至 

  • xImage
  •  

Slot 插巢

突然不知道該寫什麼 qaq 回去看了一下筆記,發現好像可以寫寫 slot
可以在父元件中插入內容到子元件的位置,也就是讓外層可以直接操作內層的 HTML 結構

<h3> Slot 插巢</h3>
<card>
	<p>由外層定義</p>
</card>
//預設值: 有定義就是定義的值,若沒有定義則是預設值
app.component('card', {
	template: `<div class="card">
		<header>元件頁首</header>
		<div class="card-body">
			<slot>
				<p>這是預設值</p>
			</slot>
		</div>
		<footer>元件頁尾</footer>
	</div>
	`
})

具名插巢

如果有很多個 slot,就需要給個名稱

<h3> Slot 插巢</h3>
<card>
	<!--改為使用 template 標籤,v-slot 若沒有名稱則為 default-->
	<template v-slot:header>header</template>
	<template v-slot:body>body</template>
	<template v-slot:footer>footer</template>
	<!--縮寫寫法-->
	<template #header>header</template>
	<template #body>body</template>
	<template #footer>footer</template>
</card>
//預設值: 讓有定義就是定義的值,若沒有定義則是預設值
app.component('card', {
	template: `<div class="card">
		<header>
			<slot name="header">元件頁首</slot>
		</header>
		<div class="card-body">
			<slot name="body">
				<p>這是預設值</p>
			</slot>
		</div>
		<footer>
			<slot name="footer">元件頁尾</slot>
		</footer>
	</div>
	`
})

作用域插槽

子元件把資料傳給父元件,讓父元件決顯示出來

<!-- PostList.vue -->
<template>
  <ul>
    <li v-for="post in posts" :key="post.pId">
      <slot :post="post"></slot>
    </li>
  </ul>
</template>

如何使用?

<PostList :posts="posts">
  <template #default="{ post }">
    <strong>{{ post.pSchool }}</strong> - {{ post.pResult1 }}
  </template>
</PostList>

Slot Props 元件插巢的 props

將插巢中的資料給外部使用
子元件

<!-- <slot :user="user"> 表示把 user 提供給父元件使用-->
<template>
  <div>
    <slot
      v-for="user in users"
      :user="user"
      :key="user.id"
    ></slot>
  </div>
</template>

<script>
export default {
  name: 'UserList',
  data() {
    return {
      users: [
        { id: 1, name: 'Alice' },
        { id: 2, name: 'Bob' }
      ]
    }
  }
}
</script>

父元件

<template>
  <UserList>
    <template v-slot:default="slotProps">
      <div>
        <p>username:{{ slotProps.user.name }}</p>
      </div>
    </template>
  </UserList>
</template>

<script>
import UserList from './UserList.vue'

export default {
  components: { UserList }
}
</script>

小結

  • 各種 slot 介紹

上一篇
Day 14|用 Pinia 管理全域狀態
下一篇
Day 16 | Mitt 跨元件傳遞資料
系列文
Vue 新手學習紀錄24
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言